package com.yeah.sinaspider.dingtalk.service.impl;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiUserGetuserinfoRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiUserGetuserinfoResponse;
import com.taobao.api.ApiException;
import com.yeah.sinaspider.dingtalk.service.DingtalkService;
import com.yeah.sinaspider.dingtalk.config.DingtalkProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class DingtalkServiceImpl implements DingtalkService {

    @Autowired
    private DingtalkProperties properties;

    private final static Logger logger = LoggerFactory.getLogger(DingtalkServiceImpl.class);

    /**
     * 获取token
     */
    private String getToken(String appkey, String appsecret) {
        try {
            DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey(appkey);
            request.setAppsecret(appsecret);
            request.setHttpMethod("GET");
            OapiGettokenResponse response = client.execute(request);
            String access =  response.getAccessToken();
            System.out.println(access);
            logger.error("Get DingTalk Token---------------------->"+access);
            return access;
        } catch (ApiException e) {
            e.printStackTrace();
        }
          return null;
    }

    /**
     *     发送工作消息
     */
    @Async
    @Override
    public String pushOaWorkMsg(Map<String,Object> map) throws ApiException {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();

            request.setAgentId(properties.getAgentId());
            request.setUseridList((String) map.get("userIds"));
            request.setToAllUser((Boolean) map.get("allUser"));
            request.setDeptIdList((String) map.get("deptIds"));

            OapiMessageCorpconversationAsyncsendV2Request.Msg message = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            message.setMsgtype("oa");
            message.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
            message.getOa().setMessageUrl((String) map.get("msgUrl"));
            message.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
            message.getOa().getHead().setBgcolor("FFBBBBBB");
            message.getOa().getHead().setText((String) map.get("headTitle"));
            message.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
//
//            List<OapiMessageCorpconversationAsyncsendV2Request.Form> formList = new ArrayList<OapiMessageCorpconversationAsyncsendV2Request.Form>(){{
//                OapiMessageCorpconversationAsyncsendV2Request.Form f = new OapiMessageCorpconversationAsyncsendV2Request.Form();
//                f.setKey((String) map.get("key1"));
//                f.setValue((String) map.get("value1"));
//                add(f);
//                f = new OapiMessageCorpconversationAsyncsendV2Request.Form();
//                f.setKey((String) map.get("key2"));
//                f.setValue((String) map.get("value2"));
//                add(f);
//            }};
//            message.getOa().getBody().setForm(formList);
            message.getOa().getBody().setTitle((String) map.get("bodyTitle"));
            message.getOa().getBody().setContent((String) map.get("bodyContent"));

            request.setMsg(message);
            OapiMessageCorpconversationAsyncsendV2Response response = client.execute(request,getToken(properties.getAppkey(),properties.getAppsecret()));
            logger.error(String.format("Ding pushOaWorkMsg [reqParam]---------------------->{%s}---[responseResult]------->{%s}",map,response.getErrcode()+"^^^^^^^^"+response.getErrmsg()));
            return response.getBody();
        }catch (Exception e){
            throw e;
        }
    }

    /**
     * 获取用户id
     * @param code 免登授权码 前端传入
     * @return 用户id
     */
    @Override
    public String getUserId(String code) throws ApiException {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
            OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
            request.setCode(code);
            request.setHttpMethod("GET");
            OapiUserGetuserinfoResponse response = client.execute(request,getToken(properties.getAppkey(),properties.getAppsecret()));
            return response.getBody();
        }catch (Exception e){
            throw e;
        }
    }

}









